<?php
namespace AuctionCore\CarResource;

/**
 * 车商查询维保结算记录model
 * Class DealerRepairPayLog
 * @package AuctionCore\CarResource
 */
class DealerRepairPayLog {

	private $dealer_id = null;

	/**
	 * 构造
	 * @param  int $car_id  车辆id
	 * @return array
	 */
	public function __construct($dealer_id) {
		$this->dealer_id = $dealer_id;
	}


	/**
	 * 整体业务逻辑判断
	 * @param $amount
	 * @return bool
	 */
	public function the_bill($amount,$bail_log,$colle_state,$repair_log_id=0){
		//查询起止和结束时间
		$prefix = C('DB_PREFIX');
		$sql = "SELECT createtime FROM {$prefix}dealer_repair_log WHERE dealer_id=".$this->dealer_id."
				and pay_state=0 and search_state=2 order by createtime asc";
		$result = M()->query($sql);

		$end = end($result);
		$first = reset($result);
		//查询次数
		$times = count($result);

		$map = array(
				'dealer_id'=>$this->dealer_id,
				'pay_state'=>0,
				'search_state'=>2,
		);
		//多次结算
		if($repair_log_id){
			$sql = "update {$prefix}dealer_repair_log set pay_state=1 where id in(select d.id from (select * from {$prefix}dealer_repair_log where dealer_id=".$this->dealer_id."
			and pay_state=0 and search_state=2 order by createtime desc LIMIT ".$repair_log_id.") as d )";

			$pay_state = M()->execute($sql);
			$times = $repair_log_id;
		}else{
			//全部结算
			$pay_state = M('dealer_repair_log')->where($map)->save(array('pay_state'=>1));
		}

		$option = array(
				'end_time'=>empty($end['createtime'])?'0000-00-00 00:00:00':$end['createtime'],
				'start_time'=>empty($first['createtime'])?'0000-00-00 00:00:00':$first['createtime'],
				'times'=>$times,
				'dealer_id'=>$this->dealer_id,
				'amount'=>$amount,
				'bl_id'=>$bail_log,
				'createtime'=>date('Y-m-d H:i:s'),
				'collection_id'=>$colle_state
		);
		$bill_state = M('dealer_repair_pay_log')->add($option);
		if($bill_state&&$pay_state){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * @param $page
	 * @param $listRows
	 */
	public function get_pay_logs($page,$listRows){
		$prefix = C('DB_PREFIX');
		$sql = "SELECT id,dealer_id,CONVERT(amount,SIGNED) as amount,date_format(start_time,'%Y-%m-%d') as start_time,
				date_format(end_time,'%Y-%m-%d') as end_time,times,date_format(createtime,'%Y-%m-%d') as createtime FROM
				{$prefix}dealer_repair_pay_log where dealer_id=".$this->dealer_id." ORDER BY createtime DESC LIMIT ".$listRows*($page-1)." ,".$listRows;
		return M()->query($sql);
	}

	/**count
	 * @return mixed
	 */
	public function get_count(){
		return M('dealer_repair_pay_log')->field('count(1) as total,CONVERT(SUM(amount),SIGNED) as pay_amount')->where('dealer_id='.$this->dealer_id)->find();
	}



}
